package com.liang.exam.controller;

import com.github.pagehelper.PageInfo;
import com.liang.exam.entity.*;
import com.liang.exam.service.StudentService;
import com.liang.exam.service.TeacherService;
import com.liang.exam.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;
    @Autowired
    private TeacherService teacherService;


    @GetMapping("/getExamInfo")
    public Result<PageInfo<Exam>> getExamInfo(Integer pageNum, Integer pageSize,String examName) {
        System.out.println("examName:"+examName);
        Map<String, Object> claims = ThreadLocalUtil.get();
       String account = (String) claims.get("account");
        PageInfo<Exam> pageInfo = studentService.examList(pageNum,pageSize,account,examName);
        List<Exam> examList = pageInfo.getList();
        for (Exam item : examList) {
            String filePath = item.getFilePath();
            if (filePath!= null &&!filePath.isEmpty()) {
                try {
                    System.out.println(filePath);
                    byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));
                    String base64Encoded = Base64.getEncoder().encodeToString(fileBytes);
                    item.setFileBase64(base64Encoded);
                    String fileName = new File(filePath).getName();
                    item.setFileName(fileName);
                } catch (IOException e) {
                    e.printStackTrace();
                    // 可以根据实际情况进行更合适的错误处理，比如记录日志、返回特定错误码的Result等
                }
            }
        }
        return Result.success(pageInfo);
    }
    @GetMapping("/getStudentInfo")
    public Result<Student> getStudentInfo() {
        Map<String, Object> claims = ThreadLocalUtil.get();
        int studentId = (int) claims.get("id");
        Student student = studentService.findById(studentId);
        return Result.success(student);
    }

    public String saveFile(MultipartFile file, String examName, String teacherName) throws IOException {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        if (fileName == null || fileName.isEmpty()) {
            throw new IOException("文件名为空");
        }
        // 获取项目根目录路径
        String projectRoot = System.getProperty("user.dir") + "/exam" + "/src";
        // 设置目标路径：项目根目录下的 uploads/Papers 文件夹
        String uploadDir = projectRoot + "/uploads" + "/" + examName + "_" + teacherName + "/Papers";
        String submitDir = projectRoot + "/uploads" + "/" + examName + "_" + teacherName + "/Answer";
        Path uploadPath = Paths.get(uploadDir);
        Path submitPath = Paths.get(submitDir);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath); // 确保目标目录存在
        }
        if (!Files.exists(submitPath)) {
            Files.createDirectories(submitPath); // 确保目标目录存在
        }
        // 生成文件路径
        Path filePath = submitPath.resolve(fileName);
        // 保存文件到目标路径
        file.transferTo(filePath.toFile());
        return filePath.toString();
    }
    @PostMapping("/uploadStudentAnswer")
    public Result<String> uploadStudentAnswer(@RequestPart("exam") Exam exam, @RequestPart(value = "file", required = false) MultipartFile file) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        String account = (String) claims.get("account");
        exam.setAccount(account);
        String teacherName = teacherService.findById(exam.getTeacherId()).getUserName();
        if (file != null && !file.isEmpty()) {
            try {
                String filePath = saveFile(file, exam.getExamName(), teacherName);
                exam.setFilePath(filePath);
            } catch (IOException e) {
                return Result.error("上传答卷失败");
            }
        }
        try {
            System.out.println(exam);
            studentService.uploadStudentAnswer(exam);

            return Result.success("上传答卷成功");
        } catch (Exception e) {
            return Result.error("上传答卷失败");
        }
    }
}
